/**
 * @file UART.cpp
 * @author bean (813023818@qq.com)
 * @brief 
 * @version 0.1
 * @date 2023-01-05
 * 
 * @copyright Copyright (c) 2023
 * 
 */
#include "UART.h"
// 组合逻辑，实现数据按位发送
// q_output：数据右移一位输出，可以把此端口屏蔽
void UART0::prc_outputs()
{
    sc_bv<8> q_temp;
    if (!sys_rst_n)
    {
        uart_txd = '1'; // 空闲状态，发送端为高电平
    }
    else if (start_flag)
    {
        // cout << "\ttx_cnt:" << tx_cnt.read() << endl;
        switch (tx_cnt.read())
        {
        case 0:
            uart_txd = '0';
            q_output.write("00000000");
            break; // 发送起始位
        case 1:
            uart_txd = tx_data.read().range(0, 0);
            q_temp = ("0", tx_data.read().range(7, 1));
            q_output.write(q_temp);
            break;
        case 2:
            uart_txd = tx_data.read().range(1, 1);
            q_temp = ("00", tx_data.read().range(7, 2));
            q_output.write(q_temp);
            break;
        case 3:
            uart_txd = tx_data.read().range(2, 2);
            q_temp = ("000", tx_data.read().range(7, 3));
            q_output.write(q_temp);
            break;
        case 4:
            uart_txd = tx_data.read().range(3, 3);
            q_temp = ("0000", tx_data.read().range(7, 4));
            q_output.write(q_temp);
            break;
        case 5:
            uart_txd = tx_data.read().range(4, 4);
            q_temp = ("00000", tx_data.read().range(7, 5));
            q_output.write(q_temp);
            break;
        case 6:
            uart_txd = tx_data.read().range(5, 5);
            q_temp = ("0000000", tx_data.read().range(7, 6));
            q_output.write(q_temp);
            break;
        case 7:
            uart_txd = tx_data.read().range(6, 6);
            q_temp = ("0000000", tx_data.read().range(7, 7));
            q_output.write(q_temp);
            break;
        case 8:
            uart_txd = tx_data.read().range(7, 7);
            q_temp = ("00000000");
            q_output.write(q_temp);
            break;
        case 9:
            uart_txd = '1';
            break; // 发送停止位
        default:
            uart_txd = '1';
            break;
        }
    }
    else
    {
        uart_txd = '1';
    }
}

void UART0::BPS_TIMER()
{ // 时序逻辑
    if (!sys_rst_n)
    {
        bps_cnt = 0;
        tx_cnt = 0;
    }
    else if (bps_cnt.read() < BPS_CNT - 1)
    {
        bps_cnt = bps_cnt.read() + 1;
        tx_cnt = tx_cnt;
    }
    else
    {
        bps_cnt = 0;
        tx_cnt = tx_cnt.read() + 1;
    }
}

void UART0::load_data()
{
    if (!sys_rst_n)
    {
        tx_flag = false;
        tx_data = "00000000";
    }
    else if (start_flag)
    {
        tx_flag = true;
        tx_data = q.read();
    }
    else if ((tx_cnt.read() == 9) && (bps_cnt.read() == BPS_CNT / 2))
    {
        tx_flag = false;
        tx_data = "00000000";
        tx_cnt = 0;
    }
    else
    {
        tx_flag = tx_flag;
        tx_data = tx_data;
    }
}
